package com.youbug.kefu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youbug.kefu.entity.DicType;
import com.youbug.kefu.entity.Dictionary;
import com.youbug.kefu.entity.User;
import com.youbug.kefu.mapper.DicTypeMapper;
import com.youbug.kefu.service.IDicTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youbug.kefu.service.IDictionaryService;
import com.youbug.kefu.vo.PageQueryVo;
import com.youbug.kefu.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 字典类型表 服务实现类
 * </p>
 *
 * @author youbug
 * @since 2023-02-12
 */
@Service
public class DicTypeServiceImpl extends ServiceImpl<DicTypeMapper, DicType> implements IDicTypeService {

    @Autowired
    private IDictionaryService dictionaryService;

    @Override
    public IPage<DicType> getDicTypePage(PageQueryVo<DicType> pageQueryVo) {

        DicType dicType = pageQueryVo.getPayload();

        Page<DicType> dicTypePage = new Page<>();

        dicTypePage.setCurrent(pageQueryVo.getCurrentPage());

        dicTypePage.setSize(pageQueryVo.getPageSize());

        QueryWrapper<DicType> wrapper = new QueryWrapper<>();

        if(StringUtils.hasText(dicType.getName())){

            wrapper.like("name", dicType.getName());
        }
        if(StringUtils.hasText(dicType.getCode())){

            wrapper.eq("code", dicType.getCode());
        }
        Page<DicType> page = this.page(dicTypePage, wrapper);

        List<Long> dicIds = page.getRecords().stream().map(DicType::getId).collect(Collectors.toList());

        QueryWrapper<Dictionary> dictionaryWrapper = new QueryWrapper<>();

        dictionaryWrapper.in("type_id", dicIds);
        dictionaryWrapper.orderByAsc("order_id");

        List<Dictionary> dictionaries = dictionaryService.list(dictionaryWrapper);

        page.getRecords().forEach(type -> {
            dictionaries.forEach(dic -> {
                if(type.getId().equals(dic.getTypeId())){
                    if(type.getItems() == null){
                        ArrayList<Dictionary> items = new ArrayList<>();
                        type.setItems(items);
                        items.add(dic);
                    }else{
                        type.getItems().add(dic);
                    }
                }
            });
        });

        return page;
    }
}
